package ex01;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by lili on 2017/8/7
 */
public class HttpServer {

    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";

    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";

    private boolean shutdown = false;

    public void await() {

        System.out.println("服务器开启，等待请求...");

        ServerSocket serverSocket = null;
        int port = 8090;

        try {
            serverSocket = new ServerSocket(port,1, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //循环等待请求到来
        while (!shutdown) {

            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;

            try {
                //阻塞
                socket = serverSocket.accept();
                //获取客户端输入流
                input = socket.getInputStream();
                output = socket.getOutputStream();

                Request request = new Request(input);
                //解析Request
                request.parse();

                Response response = new Response(output);

                response.setRequest(request);

                response.sendStaticResource();

                socket.close();

                //SHUTDOWN_COMMAND断开请求
                shutdown = request.getUri().equals(SHUTDOWN_COMMAND);


            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.await();
        //CMDER  curl http://localhost:8090/index.html
        //in brower  ie可以显示页面，chrome有错，firefox返回html代码
    }
}
